#include "base/core/os/dynamic_lib.h"
#include "base/core/os/debug.h"
#include "base/core/com_define.h"
#include <dlfcn.h>
#include <string>

DynamicLib::DynamicLib() 
{
  handle_ = NULL;
}

DynamicLib::~DynamicLib() 
{
  if (handle_) dlclose(handle_);
  handle_ = NULL;
}

int DynamicLib::Open(const char* dll_file) 
{
	if (handle_) 
	{
		dlclose(handle_);
		handle_ = NULL;
	}

	handle_ = dlopen(dll_file, RTLD_LAZY | RTLD_GLOBAL);
	if (handle_ == NULL) 
	{
		OutputFmtToConsole("file:%s,dlopen: %s\n", dll_file, dlerror());
	}
	MMO_ASSERT(handle_);
	return 0;
}

void* DynamicLib::Func(const char* func_name) 
{
	if (handle_ == NULL) 
	{
		OutputFmtToConsole("get func %s but handle is null\n", func_name);
		return NULL;
	}
	dlerror();  /* Clear any existing error */
  
	void* ret   = dlsym(handle_, func_name);
	char* error = dlerror();
	if (error != NULL) 
	{
		OutputFmtToConsole("get_func[%s], error:%s\n", func_name, error);
		return NULL;
	} 
	else return ret;
}

